
import { Checkbox, message, Pagination, Popconfirm, Table } from 'antd';
import React from 'react';
import { useEffect, useState } from 'react';
import { EmilStateType, useDispatch, useSelector } from 'umi';
import styles from './index.less'

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}


let emilTable = () => {
  // 全选反选
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  // 表格数据
  const columns = [
    {
      title: '发件人',
      width: 100,
      dataIndex: 'from',
      key: 'from',
    },
    {
      title: '收件人',
      width: 100,
      dataIndex: 'to',
      key: 'to',
    },
    {
      title: '主题',
      dataIndex: 'subject',
      key: '1',
      width: 100
    },
    {
      title: '发送时间',
      dataIndex: 'time',
      key: '2',
      width: 130
    },
    {
      title: '操作',
      key: 'operation',
      width: 70,
      render: (operation:any) => 
      <Popconfirm 
         title="确认删除这个邮件？" 
         okText="确认" cancelText="取消" 
         onConfirm={function() {DeleteItem(operation)}}>
            <a href="#">删除</a>
      </Popconfirm>
    },
  ];
  const dispatch = useDispatch()
  let [pageNum,setPage] = useState(1)
  const { EmilList, EmilLength } = useSelector((state:{ emil: EmilStateType }) => state.emil)


  // 点击分页
  let changePage = (page: number) =>{
    setPage(page)
    dispatch({
      type: 'emil/getEmilList',
      payload:{
        page
      }
    })
  }

  // 邮件删除数据
  function DeleteItem(operation:any) {
      dispatch({
        type: 'emil/delEmilList',
        payload:{
          id: operation.key,
          page: pageNum
        }
      })
      // 删除成功提示
      message.success('操作成功');
  }
  

  // 表格数据
  const data = EmilList.map((item: { id: string; from: string; to: string; subject: string; createAt: string | number | Date; }) =>{
    return {
      key:item.id,
      from: item.from,
      to: item.to,
      subject: item.subject,
      time: new Date(item.createAt).toLocaleString()
    }
  })
  
  return (
    <div>
      <Table 
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          columns={columns} 
          dataSource={data} 
          scroll={{ x: 1500 }} 
          pagination={false}/>
      <div className={styles.emil_footer}>
        <p>共{EmilLength}条数据</p>
        <Pagination
          onChange={changePage} 
          defaultCurrent={1} 
          defaultPageSize={12} 
          total={EmilLength} />
      </div>
    </div>
  )
}

export default emilTable

